package com.zookeeper.case3;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @author WangGuoLiang
 * @program ZooKeeper
 * @description 使用Curator框架实现分布式锁
 * @create 2021-09-05 15:51
 **/
public class CuratorLockTest {
    public static void main(String[] args) {
        //创建分布式锁1
        InterProcessMutex interProcessMutex = new InterProcessMutex(getCuratorFramework(), "/locks");
        //创建分布式锁2
        InterProcessMutex interProcessMutex1 = new InterProcessMutex(getCuratorFramework(), "/locks");

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    interProcessMutex.acquire();
                    System.out.println("线程1获取到锁");
                    //再次获取锁
                    interProcessMutex.acquire();
                    System.out.println("线程1再次获取到锁");
                    Thread.sleep(5000);
                    //释放锁
                    interProcessMutex.release();
                    System.out.println("线程1释放锁");
                    interProcessMutex.release();
                    System.out.println("线程1再次释放锁");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    interProcessMutex1.acquire();
                    System.out.println("线程2获取到锁");
                    //再次获取锁
                    interProcessMutex1.acquire();
                    System.out.println("线程2再次获取到锁");
                    Thread.sleep(5000);
                    //释放锁
                    interProcessMutex1.release();
                    System.out.println("线程2释放锁");
                    interProcessMutex1.release();
                    System.out.println("线程2再次释放锁");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private static CuratorFramework getCuratorFramework() {
        ExponentialBackoffRetry exponentialBackoffRetry = new ExponentialBackoffRetry(3000, 3);
        CuratorFramework build = CuratorFrameworkFactory.builder().connectString("47.106.199.16:2181")
                .connectionTimeoutMs(2000)
                .sessionTimeoutMs(2000)
                .retryPolicy(exponentialBackoffRetry).build();
        //启动客户端
        build.start();
        return build;
    }
}

